package utils;

import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;

public class CryptUtils {
	
	private static String Key = "Ingebook";

	public static String StringToBytes(String str){

		byte[] KeyData = Key.getBytes();
		SecretKeySpec KS = new SecretKeySpec(KeyData, "Blowfish");
		Cipher cipher = null;
		try {
			cipher = Cipher.getInstance("Blowfish");
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchPaddingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// initialise cipher to with secret key
		try {
			cipher.init(Cipher.ENCRYPT_MODE, KS);
		} catch (InvalidKeyException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// encrypt message
		String encrypted = null;
		try {
			encrypted = new String(cipher.doFinal(str.getBytes()));
		} catch (IllegalBlockSizeException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (BadPaddingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return encrypted;
	}
	
	public static String BytesToString(String str){
		
		byte[] KeyData = Key.getBytes();
		SecretKeySpec KS = new SecretKeySpec(KeyData, "Blowfish");
		Cipher cipher = null;
		String decrypt = "";
		
		System.out.println(str.trim()+" "+str);
		try {
			cipher = Cipher.getInstance("Blowfish");
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchPaddingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// initialise cipher to with secret key
		try {
			cipher.init(Cipher.DECRYPT_MODE, KS);
		} catch (InvalidKeyException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// encrypt message
		try {
			byte[] decrypted = cipher.doFinal(str.getBytes());
			decrypt = new String(decrypted);
		} catch (IllegalBlockSizeException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (BadPaddingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return decrypt;
		
	}
	
	
}
